<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {ElNotification, type FormInstance, type FormRules} from "element-plus";
import {User, Lock, Key} from "@element-plus/icons-vue";
import {getTime} from "@/utils";
import {useRoute, useRouter} from "vue-router";
import {getCode} from "@/api/admin";
import type {TLoginForm} from "@/api/admin/type.ts";
import useAdmin from "@/store/modules/admin.ts";
// 指定ref来获取表单实例
const loginFormRef = ref<FormInstance>()
// 指定ref来获取图形验证码存放的位置
const captchaRef = ref();
// 定义loading
const isLoading = ref<boolean>(false);
const $router = useRouter();
const $route = useRoute();
// 获取管理员仓库信息
const adminStore = useAdmin();
// 指定表单绑定的数据
const loginForm = reactive<TLoginForm>({
    // 管理员账号
    adminName: 'yuma',
    // 密码
    password: '11111111',
    // 验证码
    captcha:""
})
// 当管理员账号输入框失去焦点会触发
const validateAdminName = (_: any, value: any, callback: any) => {
    // 判断输入的内容是否为空字符串
    if (value === '') {
        // 给予错误的提示
        callback(new Error('请输入管理员账号'));
    }else callback();
}
// 当密码输入框失去焦点会触发
const validatePassword = (_: any, value: any, callback: any) => {
    // 判断输入的内容是否为空字符串
    if (value === '') {
        callback(new Error('请输入管理员密码'))
    }else callback();
}
// 当验证码输入框失去焦点会触发
const validateCaptcha = (_: any, value: any, callback: any) => {
    // 判断输入的内容是否为空字符串
    if (value.length !== 4) {
        callback(new Error('请输入正确验证码'))
    }else callback();
}
// 表单验证规则
const rules = reactive<FormRules<typeof loginForm>>({
    // 每一个数据可以匹配多个规则，数组中的每一个元素即是一个规则
    adminName: [{ validator: validateAdminName, trigger: 'blur' }],
    password: [{ validator: validatePassword, trigger: 'blur' }],
    captcha: [{ validator: validateCaptcha, trigger: 'blur' }],
})
// 提交表单触发的函数
const submitForm = function(){
    // 判断输入的内容是否合法，如果不合法没有必要收集
    if(!loginFormRef.value) return;
    loginFormRef.value.validate(async function(valid){
        if (!valid) return;
        try{
            isLoading.value = true;
            await adminStore.postLoginAsync(loginForm);

            ElNotification({
                title: '登陆成功',
                message: loginForm.adminName+','+getTime()+'好！欢迎回来!',
                type: 'success',
            });

            const returnPath = ($route.query.returnUrl || "/") as string;
            $router.push(returnPath).then(()=>{
                isLoading.value = false;
            });

        }catch (err){
            isLoading.value = false;
            // 更新验证码
            getCodeAsync();
        }
    })
}
// 获取图形验证码
const getCodeAsync = async ()=>captchaRef.value.innerHTML = await getCode();
// 组件挂载完毕之后
onMounted(()=>{
    // 获取验证码
    getCodeAsync();
})
</script>

<template>
    <div class="login-container">
        <el-card style="margin-bottom: 100px">
            <el-space direction="vertical" :size="20">
                <h3>御医坊管理系统登陆</h3>
                <el-form
                    ref="loginFormRef"
                    style="width: 360px"
                    :model="loginForm"
                    status-icon
                    :rules="rules"
                    class="demo-ruleForm"
                    @keyup.enter="submitForm()"
                >
                    <el-form-item prop="adminName">
                        <el-input
                             :prefix-icon="User"
                             placeholder="请输入管理员账号"
                             v-model="loginForm.adminName"
                             autocomplete="off" />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input
                            :prefix-icon="Lock"
                            placeholder="请输入管理员密码"
                            v-model="loginForm.password"
                            type="password"
                            autocomplete="off"
                        />
                    </el-form-item>
                    <el-form-item style="width: 250px;" prop="captcha">
                        <el-input
                            :prefix-icon="Key"
                            placeholder="请输入验证码"
                            v-model="loginForm.captcha"
                            autocomplete="off"
                        >
                            <template #append>
                                <span @click="getCodeAsync" style="cursor:pointer;width:80px;height: 30px;" ref="captchaRef"></span>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item  style="margin-bottom: 10px">
                        <el-button :loading="isLoading" style="width:100%" type="primary" @click="submitForm()">登陆</el-button>
                    </el-form-item>
                </el-form>
            </el-space>

        </el-card>
    </div>


</template>

<style scoped lang="less">
.login-container{
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}
:deep(.el-input-group__append){
    padding:0;
}
</style>